<?php
/*
Written by Best Flash Solutions, Inc  
See:
	http://www.bestflashsolutions.com
Contact me: contact@bestflashsolutions.com
*/

require('config.php');

function getConnection($user, $pass, $mysqladd, $dbname) {
		//CONNECT TO MYSQL
		$link=mysql_connect($mysqladd,$user,$pass) or die('<Error>Database Error: ' . mysql_error() . '</Error>');
		//CONNECT TO DATABASE
		mysql_select_db($dbname, $link) or die('<Error>Could not connect to DB: ' . mysql_error() . '</Error>');
		return $link;			
}

//Check correc username and password
function checkLogin($username, $password) {
		$result = mysql_query("SELECT * FROM `user` WHERE username='" . $username . "' AND password='" . $password . "'");
		$rs = -1;
		while($row = mysql_fetch_array($result)) {
				
				$rs = $row['joining'];
				break;
		}
		mysql_free_result($result); 
		return $rs;
}
//Get user permission
function getUserPermissionAndId($username, $password) {
		$result = mysql_query("SELECT * FROM `user` WHERE username='" . $username . "' AND password='" . $password . "'");
		//$ap = "normal";
		$ap = "' permission='student' id='0";// . getUserPermission($username, $password)
		while($row = mysql_fetch_array($result)) {	
				//echo "<result joining='" . checkLogin($username, $password) . "' permission='" . getUserPermission($username, $password) . "'/>";	
				$ap = "' permission='".$row['permission']."' userid='".$row['id']."";
				break;
		}
		mysql_free_result($result); 
		return $ap;
}

//Update login status
//Status = joining = 1/0
function updateLoginStatus($username, $password, $status) {
		mysql_query("UPDATE user SET joining=" . $status . " WHERE username='" . $username . "' AND password='" . $password . "'")
										or die(mysql_error());  
		return (checkLogin($username, $password)==$status ? 1 : 0);
}

//update user in room
//Status = joining = 1/0
function updateRoomManager($username, $roomId, $cam_width, $cam_height) {
		//echo "INSERT INTO roommanager(roomId, joinUser, cam_width, cam_height) VALUES(" . $roomId . ",'" . $username . "'," . $cam_width . "," . $cam_height . ")";
		deleteRoomManager($username, $roomId);
		mysql_query("INSERT INTO roommanager(roomId, joinUser, cam_width, cam_height) VALUES(" . $roomId . ",'" . $username . "'," . $cam_width . "," . $cam_height . ")")
										or die(mysql_error());  
		return 1;
}

//remove user out of room
//Status = joining = 1/0
function deleteRoomManager($username, $roomId) {
		//echo "INSERT INTO roommanager(roomId, joinUser) VALUES(" . $roomId . ",'" . $username . "')";
		mysql_query("DELETE FROM roommanager WHERE roomId=" . $roomId . " AND joinUser='" . $username . "'")
										or die(mysql_error());  
		return 1;
}

//Get list active rooms
function getListActiveRoom() {
		/*$result = mysql_query("SELECT room.*, count(room.roomID) as njoiner FROM room INNER JOIN roommanager ON room.roomID=roommanager.roomId GROUP BY room.roomID");*/
		$result = mysql_query("SELECT * FROM roomactive as ra INNER JOIN room as ro ON ra.roomId=ro.roomId GROUP BY ro.roomID");		
		$rs = "";
		while($row = mysql_fetch_array($result)) {
				$countJoiners = 0;
				$roommanresult = mysql_query("SELECT * FROM roommanager WHERE roomId=".$row["roomId"]."");
				if(mysql_num_rows($roommanresult) > 0)
					$countJoiners = mysql_num_rows($roommanresult);
				
				$rs = $rs . "<room>\n";
				$rs = $rs . "<roomId>" . $row["roomId"] . "</roomId>\n";
				$rs = $rs . "<roomName>" . $row["roomName"] . "</roomName>\n";
				$rs = $rs . "<description>" . $row["description"] . "</description>\n";
				$rs = $rs . "<creator>" . $row["creator"] . "</creator>\n";
				$rs = $rs . "<GUID>" . $row["GUID"] . "</GUID>\n";
				$rs = $rs . "<status>" . $row["status"] . "</status>\n";
				$rs = $rs . "<createDate>" . $row["createDate"] . "</createDate>\n";
				$rs = $rs . "<njoiner>" . $countJoiners . "</njoiner>\n";
				$rs = $rs . "</room>\n";
		}
		mysql_free_result($result);
		return $rs;		
}

//get list of joiners in room
function getRoomJoiners($roomId) {
		/*$result = mysql_query("SELECT * FROM roommanager WHERE roomId=" . $roomId . " ORDER BY joinUser");
		$rs = "";
		while($row = mysql_fetch_array($result)) {
				$rs = $rs . "<joiner cam_width=\"" . $row["cam_width"] . "\" cam_height=\"" . $row["cam_height"] . "\">" . $row["joinUser"] . "</joiner>\n";
		}
		mysql_free_result($result);
		return $rs;		*/
		
		$result = mysql_query("SELECT * FROM roommanager as rm INNER JOIN user as us 
							    ON rm.joinUser=us.username WHERE rm.roomId=" . $roomId . " ORDER BY rm.joinUser");
		$rs = "";
		while($row = mysql_fetch_array($result)) {
				$results = mysql_query("SELECT vid_guid FROM videohistory WHERE vid_user='".$row["joinUser"]."' ORDER BY vid_id DESC LIMIT 1");
				$vidguid = "none";
				while($rows = mysql_fetch_array($results))
					$vidguid = $rows["vid_guid"];
					
				$rs = $rs . "<joiner cam_width=\"" . $row["cam_width"] . "\" cam_height=\"" . $row["cam_height"] . "\" permission=\"" . $row["permission"] . "\" userid=\"" . $row["id"] . "\" vidguid=\"" . $vidguid ."\">" . $row["joinUser"] . "</joiner>\n";
		}
		mysql_free_result($result);
		return $rs;		
}

//get room information
function getRoom($GUID) {
		$result = mysql_query("SELECT * FROM room WHERE GUID='" . $GUID . "'");
		$rs = "";
		while($row = mysql_fetch_array($result)) {
				$rs = $rs . "<room>\n";
				$rs = $rs . "<roomId>" . $row["roomId"] . "</roomId>\n";
				$rs = $rs . "<roomName>" . $row["roomName"] . "</roomName>\n";
				$rs = $rs . "<description>" . $row["description"] . "</description>\n";
				$rs = $rs . "<creator>" . $row["creator"] . "</creator>\n";
				$rs = $rs . "<GUID>" . $row["GUID"] . "</GUID>\n";
				$rs = $rs . "<status>" . $row["status"] . "</status>\n";
				$rs = $rs . "<createDate>" . $row["createDate"] . "</createDate>\n";
				$rs = $rs . "</room>\n";
				break;
		}
		mysql_free_result($result);
		return $rs;	
}

//Create new room
function createRoom($creator, $roomName, $roomDescription="", $GUID) {
		$now= date( 'Y-m-d H:i:s', time());
		mysql_query("INSERT INTO room(roomName, description, creator, GUID, createDate) VALUES('" . $roomName . "','" . $roomDescription . "','" . $creator . "','" . $GUID . "','" . $now . "')");
		
		$result = mysql_query("SELECT roomId FROM room ORDER BY roomId DESC LIMIT 1");
		
		while($row = mysql_fetch_array($result))
			mysql_query("INSERT INTO roomactive(roomId) VALUES(" .$row["roomId"] . ")");
		
		return getRoom($GUID);
}

//Create Message History
function addMessageHistory($rootPath, $filesavename, $filesave, $GUID, $roomtype) {
	$filename = '../djData/'.$GUID;
	if(!file_exists($filename))
		mkdir($filename);
		
	$filename .= '/'. $filesavename.'.xml';
		
	$fh = fopen($filename, 'w') or die("can't open file");
	fwrite($fh, $filesave);
	fclose($fh);
	
	$user = "public";
	if($roomtype == 1)
		$user = $filesavename;
		
	$result = mysql_query("SELECT * FROM chathistory WHERE chat_filename='".$filesavename."' AND chat_room_guid='".$GUID."'");
	
	if (mysql_num_rows($result) == 0){
		mysql_query("INSERT INTO chathistory(chat_filename, chat_room_guid, chat_user, chat_room_type) VALUES('" . $filesavename . "','" . $GUID . "','" . $user . "','" . $roomtype ."')");
	}
}

//view Message History
function viewMessageHistory($rootPath, $GUID) {
	$result = mysql_query("SELECT * FROM chathistory WHERE chat_room_guid='".$GUID."'");
	$xmlData = "";
	
	while($row = mysql_fetch_array($result)){
		$filename = 'http://'.$rootPath.'/djData/'.$GUID.'/'.$row["chat_filename"].".xml";
		$xmlData .=  "<usermessage chatuser='".$row["chat_user"]."'>";
		if(get_http_response_code($filename) == "404" || get_http_response_code($filename) == "403"){
			$xmlData .= "";
		}else $xmlData .= file_get_contents($filename);	
		$xmlData .=  "</usermessage>";
	}	
	return $xmlData;
}

//Retrieve Message History
function retreiveMessageHistory($rootPath, $filename, $GUID) {
	$filename = 'http://'.$rootPath.'/djData/'.$GUID.'/'.$filename;
	if(get_http_response_code($filename) == "404" || get_http_response_code($filename) == "403"){
		$file = "";
	}else $file = file_get_contents($filename);
	return $file;
}

function get_http_response_code($url) {
    $headers = get_headers($url);
    return substr($headers[0], 9, 3);
}

// Video History
function addVideoHistory($vidGuid, $vidUser, $vidRoom, $videMute){	
	$result = mysql_query("SELECT * FROM videohistory WHERE vid_user='".$vidUser."' AND vid_guid='".$vidGuid."'");
	
	if (mysql_num_rows($result) > 0){
		if($videMute == 1){
			$retString = "Already Exist"; 
			while($row = mysql_fetch_array($result)){
				if($row["vid_unmute"] == 0){
					mysql_query("UPDATE videohistory SET vid_unmute=1 WHERE vid_id=" . $row["vid_id"] . "")
										or die(mysql_error());  
					$retString = "Update Complete"; 
				}
				break;
			}
			return $retString; 
		}else
			return "Already Exist"; 		
	}else{
		$now= date( 'Y-m-d H:i:s', time());
		mysql_query("INSERT INTO videohistory(vid_guid, vid_user, vid_room, vid_datetime, vid_unmute) VALUES('" . $vidGuid . "','" . $vidUser . "','" . $vidRoom . "','" . $now. "', ".$videMute.")");
		return "Insert History";
	}	
}

function getVideoHistory($GUID) {
		//$result = mysql_query("SELECT * FROM videohistory WHERE vid_room='" . $GUID . "'");
		$result = mysql_query("SELECT * FROM videohistory AS vh INNER JOIN user AS us ON vh.vid_user=us.username WHERE vid_room='" . $GUID . "' AND vid_unmute=1");
		$rs = "";
		$i = 0;
		while($row = mysql_fetch_array($result)) {
			if($i > 0)
				$rs .= "\n";
			$i++;
			
			$rs .= "<item no='".$i."' vidGuid='".$row["vid_guid"]."' user='".$row["vid_user"]."' vidDate='".$row["vid_datetime"]."'  permission='".$row["permission"]."'/>";
		}
		mysql_free_result($result);
		return $rs;	
}

// Drop Box List
function getDropOffList($typeList, $teacherName, $roomGuid) {
		//$result = mysql_query("SELECT * FROM videohistory WHERE vid_room='" . $GUID . "'");
		$wherecommand = "att_room_guid='".$roomGuid."'";
		if($typeList == 0)
			$wherecommand = "att_room_guid='".$roomGuid."' AND att_teachername='".$teacherName."'";
		
		$result = mysql_query("SELECT * FROM attachment WHERE ".$wherecommand);
		$rs = "";
		$i = 0;
		while($row = mysql_fetch_array($result)) {
			if($i > 0)
				$rs .= "\n";
			$i++;
			
			$rs .= "<item no='".$i."' roomid='".$row["att_room_guid"]."' fname='".$row["att_filename"]."' user='".$row["att_teachername"]."' note='".$row["att_note"]."'  listDate='".$row["att_date"]."'/>";
		}
		mysql_free_result($result);
		return $rs;	
}

function removeSelectedList($filename, $roomGuid, $fileowner) {
	$file = '../djData/'.$roomGuid.'/saveattachment/'.$filename;
	if(file_exists($file)){
		unlink($file);
		mysql_query("DELETE FROM attachment WHERE att_teachername='".$fileowner."' AND att_filename='".$filename."' AND att_room_guid='".$roomGuid."'");
		return "Delete File Success";
	}else return "File Not Exist".$file; 	
}

function removeRoom($roomid){
	mysql_query("DELETE FROM roomactive WHERE roomId=".$roomid."");
	return "Delete File Success";
}

if (!isset($_POST['command'])) {
		echo "<Error>Command request</Error>";
		exit(-1);
}

$command = $_POST['command'];

$username = "";
$password = "";
$status = "";
$GUID = "";
$roomId = 0;
$roomDescription = "";
$roomName = "";

//Get params
if (isset($_POST['username'])) 
		$username = $_POST['username'];
if (isset($_POST['password']))
		$password = $_POST['password'];
if (isset($_POST['status']))
		$status = $_POST['status'];
if (isset($_POST['GUID']))
		$GUID= $_POST['GUID'];
if (isset($_POST['roomName']))
		$roomName = $_POST['roomName'];
if (isset($_POST['roomDescription']))
		$roomDescription = $_POST['roomDescription'];
if (isset($_POST['roomId']))
		$roomId = $_POST['roomId'];


$conn = getConnection($mysqluser, $mysqlpass, $mysqladd, $databasename);

//Process for each commands
if ($command=="checklogin") {		
		//echo "<result joining='" . checkLogin($username, $password) . "' permission='" . getUserPermission($username, $password) . "'/>";	
		echo "<result joining='" . checkLogin($username, $password) . getUserPermissionAndId($username, $password) . "'/>";
}
else if ($command=="updatelogin") {
		echo "<result>" . updateLoginStatus($username, $password, $status) . "</result>";
}
else {
		if (0) {//checkLogin($username, $password)!=1) {
				echo "<Error>Not login yet</Error>";
		}
		else {	
			if ($command=="activeroom") {
					echo "<result>\n" . getListActiveRoom() . "</result>";
			}
			else if ($command=="getroom") {
					echo "<result>" . getRoom($GUID) . "</result>";		
			}
			else if ($command=="createroom") {
					if (empty($username) || empty($roomName) || empty($GUID))
							$rs = "Some information is empty";
					else
							$rs = createRoom($username, $roomName, $roomDescription, $GUID);		
					echo "<result>" . $rs . "</result>";
		  }
			else if ($command=="roomjoiners") {
					echo "<result>" . getRoomJoiners($roomId) . "</result>";		
			}
			else if ($command=="updateroommanager") {
					$cam_width = $_POST['cam_width'];
					$cam_height = $_POST['cam_height'];
					echo "<result>" . updateRoomManager($username, $roomId, $cam_width, $cam_height) . "</result>";		
			}
			else if ($command=="videohistory") {
					$vidguid = $_POST['vidguid'];
					$viduser = $_POST['viduser'];
					$vidroom = $_POST['vidroom'];
					$videMute = $_POST['videMute'];
					echo "<result>" . addVideoHistory($vidguid, $viduser, $vidroom, $videMute) . "</result>";		
			}
			else if ($command=="addmessagehistory") {
					$roothpath = $_POST['roothpath'];
					$filesavename = $_POST['filesavename'];
					$roomguid = $_POST['roomguid'];
					$filesave = $_POST['filesave'];
					$roomtype = $_POST['roomtype'];
					echo "<result>" . addMessageHistory($roothpath, $filesavename, $filesave, $roomguid, $roomtype) . "</result>";		
			}
			else if ($command=="retrievemessagehistory") {
					$roothpath = $_POST['roothpath'];
					$filesavename = $_POST['filesavename'];
					$roomguid = $_POST['roomguid'];
					echo "<result>" . retreiveMessageHistory($roothpath, $filesavename, $roomguid) . "</result>";		
			}
			else if ($command=="viewmessagehistory") {
					$roothpath = $_POST['roothpath'];
					$roomguid = $_POST['roomguid'];
					echo "<result>" . viewMessageHistory($roothpath, $roomguid) . "</result>";		
			}
			else if ($command=="getdropofflist") {
					$type = $_POST['type'];
					$roomguid = $_POST['roomguid'];
					$teachername = $_POST['teachername'];
					echo "<result>" . getDropOffList($type, $teachername, $roomguid) . "</result>";		
			}
			else if ($command=="deleteroom") {
					$roomid = $_POST['roomid'];
					echo "<result>" . removeRoom($roomid) . "</result>";	
			}
			else if ($command=="removeselectedlist") {
					$roomguid = $_POST['roomguid'];
					$filename = $_POST['filename'];
					$fileowner = $_POST['fileowner'];
					echo "<result>" .removeSelectedList($filename, $roomguid, $fileowner). "</result>";			
			}
			else if ($command=="getvideohistory") {
					$vidroom = $_POST['vidroom'];
					echo "<result>" . getVideoHistory($vidroom) . "</result>";		
			}
			else if ($command=="deleteroommanager") {
					echo "<result>" . deleteRoomManager($username, $roomId) . "</result>";		
			}
			else
					echo "<Error>Command not found</Error>";
					
		}
}								

mysql_close($conn);
?>
